package com.scott.factory.lesson04.spring.imitate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

import com.scott.factory.lesson05.jdom.JdomSample;

/**
 * 模拟spring的ClassPathXmlApplicationContext
 */
public class ClassPathXmlApplicationContext implements BeanFactory {

	private Map<String,Object> container = new HashMap<String,Object>();
	
	public ClassPathXmlApplicationContext(String fileName){
		
		
		try {
			SAXBuilder sb = new SAXBuilder();
			//读取配置文件applicationContext.xml
			Document doc = sb.build(JdomSample.class.getClassLoader().getResourceAsStream(fileName));
			Element root = doc.getRootElement();
			List<?> list = XPath.selectNodes(root, "/beans/bean");
			System.out.println(list.size());
			
			for (int i = 0; i < list.size(); i++) {
				Element bean = (Element) list.get(i);
				
				//拿到id属性对应的值
				String id = bean.getAttributeValue("id");
				System.out.println(id);
				
				String clz= bean.getAttributeValue("class");
				System.out.println(clz);
				
				Object object = Class.forName(clz).newInstance();
				container.put(id, object);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		
	}
	
	@Override
	public Object getBean(String id) {
		
		return container.get(id);
	}

}
